package com.example.booksdeal.fragment;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.booksdeal.BmobDBO.BooksDetail;
import com.example.booksdeal.BmobDBO.User;
import com.example.booksdeal.R;
import com.example.booksdeal.util.DBOpenHelper;
import com.example.booksdeal.util.ImageUtils;
import com.longsh.optionframelibrary.OptionBottomDialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

import static android.app.Activity.RESULT_OK;

public class F3Fragment extends Fragment {

    private DBOpenHelper dbOpenHelper;  //声明DBOpenHelper对象
    private EditText title,price,oprice,detail,address;
    private Spinner type,hownew;
    private Button enter;
    private RadioGroup func;
    private ImageView image;
    private String mtitle,mprice,moprice,mdetail,maddress,mtype,mhownew,mfuc,username;
    private Bitmap bitmap;

    //两个Spinner的适配器
    private List<String> type_list;
    private List<String> hownew_list;
    private ArrayAdapter<String> type_adapter;
    private ArrayAdapter<String> hownew_adapter;
    Intent intent_photo;

    //拍照功能参数
    private static final int TAKE_PHOTO = 1;
    private static final int CHOOSE_PHOTO = 2;
    private final static int CROP_IMAGE = 3;

    //imageUri照片真实路径
    private Uri imageUri;
    //照片存储
    File filePath;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.f3_fragment,container,false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        dbOpenHelper = new DBOpenHelper(getActivity(),"db_booksdeal.db",null,1);  //实例化DBOpenHelper对象，用来创建数据库
        Bundle bundle = getActivity().getIntent().getExtras();
        username = bundle.getString("username");
        initview(view);
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Image(view);
            }
        });
        enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                publish();
            }
        });
    }

    public void initview(View view)  //初始化UI
    {
        enter = view.findViewById(R.id.enter);
        image = view.findViewById(R.id.image);
        type = view.findViewById(R.id.type);
        hownew = view.findViewById(R.id.hownew);
        title = view.findViewById(R.id.title);
        price = view.findViewById(R.id.price);
        oprice = view.findViewById(R.id.oprice);
        detail = view.findViewById(R.id.detail);
        address = view.findViewById(R.id.address);
        func = view.findViewById(R.id.func);

        //新数据
        type_list = new ArrayList<String>();
        type_list.add("请选择图书类型");
        type_list.add("高数");
        type_list.add("外语");
        type_list.add("政治");
        type_list.add("计算机");
        type_list.add("旅游");
        type_list.add("管理");
        type_list.add("考试");
        type_list.add("其他");
        hownew_list = new ArrayList<String>();
        hownew_list.add("十成新");
        hownew_list.add("九五新");
        hownew_list.add("九成新");
        hownew_list.add("八五新");
        hownew_list.add("七成新");
        hownew_list.add("六成新");
        hownew_list.add("五成新");
        //适配器
        type_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, type_list);
        hownew_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,hownew_list);
        //设置样式
        type_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        hownew_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        type.setAdapter(type_adapter);
        hownew.setAdapter(hownew_adapter);
    }

    public void Image(View view)//图片控件点击事件
    {
        List<String> stringList = new ArrayList<String>();
        stringList.add("拍照");
        stringList.add("从相册选择");
        final OptionBottomDialog optionBottomDialog = new OptionBottomDialog(getActivity(), stringList);
        optionBottomDialog.setItemClickListener(new AdapterView.OnItemClickListener() {
        //点击事件
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //取消底部弹框
                //optionBottomDialog.dismiss();
                switch (position) {
                    case 0:
                        //启动相机程序
                        //隐式Intent
                        intent_photo = new Intent( "android.media.action.IMAGE_CAPTURE" );
                        //putExtra()指定图片的输出地址，填入之前获得的Uri对象
                        imageUri = ImageUtils.getImageUri( getActivity() );
                        intent_photo.putExtra( MediaStore.EXTRA_OUTPUT, imageUri );
                        // 需要调用到相机授权的时候判断一下。如果没有授权就弹出MaterialDialog提示用户进行授权。
                        if (Build.VERSION.SDK_INT >= 23) {
                            int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
                            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                                ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.CAMERA},222);
                                return;
                            }else{
                                startActivityForResult( intent_photo, TAKE_PHOTO );
                            }
                        } else {
                            startActivityForResult( intent_photo, TAKE_PHOTO );
                        }

                        //底部弹框消失
                        optionBottomDialog.dismiss();
                        break;
                    case 1:
                        //测试使用，验证是否为position= 1
                        //Toast.makeText(RegisterIn.this,"position 1", Toast.LENGTH_SHORT ).show();
                        //打开相册
                        openAlbum();
                        //底部弹框消失
                        optionBottomDialog.dismiss();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    // 接收MaterialDialog返回的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            //就像onActivityResult一样这个地方就是判断你是从哪来的。
            case 222:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    startActivityForResult( intent_photo, TAKE_PHOTO );
                } else {
                    // Permission Denied
                    Toast.makeText(getActivity(), "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //打开相册
    private void openAlbum() {
        Intent intent_album = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI );

        startActivityForResult( intent_album, CHOOSE_PHOTO );
    }

    //剪切图片
    private void startImageCrop(File saveToFile,Uri uri) {
        if(uri == null){
            return ;
        }
        Intent intent = new Intent( "com.android.camera.action.CROP" );
        Log.i( "Test", "startImageCrop: " + "执行到压缩图片了" + "uri is " + uri );
        intent.setDataAndType( uri, "image/*" );//设置Uri及类型
        //uri权限，如果不加的话，   会产生无法加载图片的问题
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra( "crop", "true" );//
        intent.putExtra( "aspectX", 1 );//X方向上的比例
        intent.putExtra( "aspectY", 1 );//Y方向上的比例
        intent.putExtra( "outputX", 450 );//裁剪区的X方向宽
        intent.putExtra( "outputY", 450 );//裁剪区的Y方向宽
        intent.putExtra( "scale", true );//是否保留比例
        intent.putExtra( "outputFormat", Bitmap.CompressFormat.PNG.toString() );
        intent.putExtra( "return-data", false );//是否将数据保留在Bitmap中返回dataParcelable相应的Bitmap数据，防止造成OOM，置位false
        //判断文件是否存在
        //File saveToFile = ImageUtils.getTempFile();
        if (!saveToFile.getParentFile().exists()) {
            saveToFile.getParentFile().mkdirs();
        }
        //将剪切后的图片存储到此文件
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveToFile));
        Log.i( "Test", "startImageCrop: " + "即将跳到剪切图片" );
        startActivityForResult( intent, CROP_IMAGE );
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //需要对拍摄的照片进行处理编辑
                    //拍照成功的话，就调用BitmapFactory的decodeStream()方法把图片解析成Bitmap对象，然后显示
                    Log.i( "Test", "onActivityResult TakePhoto : "+imageUri );
                    //Bitmap bitmap = BitmapFactory.decodeStream( getContentResolver().openInputStream( imageUri ) );
                    //takephoto.setImageBitmap( bitmap );
                    //设置照片存储文件及剪切图片
                    File saveFile = ImageUtils.getTempFile();
                    filePath = ImageUtils.getTempFile();
                    startImageCrop( saveFile,imageUri );
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //选中相册照片显示
                    Log.i( "Test", "onActivityResult: 执行到打开相册了" );
                    try {
                        imageUri = data.getData(); //获取系统返回的照片的Uri
                        Log.i( "Test", "onActivityResult: uriImage is " +imageUri );
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getActivity().getContentResolver().query(imageUri,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String path = cursor.getString(columnIndex);  //获取照片路径
                        cursor.close();
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        //                        photo_taken.setImageBitmap(bitmap);
                        //设置照片存储文件及剪切图片
                        File saveFile = ImageUtils.setTempFile( getActivity() );
                        filePath = ImageUtils.getTempFile();
                        startImageCrop( saveFile,imageUri );
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CROP_IMAGE:
                if(resultCode == RESULT_OK){
                    Log.i( "Test", "onActivityResult: CROP_IMAGE" + "进入了CROP");
                    // 通过图片URI拿到剪切图片
                    //bitmap = BitmapFactory.decodeStream( getContentResolver().openInputStream( imageUri ) );
                    //通过FileName拿到图片
                    bitmap = BitmapFactory.decodeFile( filePath.toString() );
                    //把裁剪后的图片展示出来
                    image.setImageBitmap( bitmap );
//                    ImageUtils.Compress( bitmap );
                    Log.i("Test", "onActivityResult: " + bitmap);
                }
                break;
            default:
                break;
        }
    }

    // 确认发布
    private void publish() {
        if(oprice.getText().toString().trim().isEmpty()||Double.parseDouble(oprice.getText().toString())==0)
            oprice.setText("0");
        if(bitmap == null)
        {
            Toast.makeText(getActivity(),"少年不传照片怎么卖啊",Toast.LENGTH_SHORT).show();
        }
        else if(title.getText().toString().trim().isEmpty())
        {
            Toast.makeText(getActivity(),"给书书来个名字呗",Toast.LENGTH_SHORT).show();
        }
        else if(type.getSelectedItem().toString().trim().length()>4)
        {
            Toast.makeText(getActivity(),"给个分类呗",Toast.LENGTH_SHORT).show();
        }
        else if(price.getText().toString().isEmpty())
        {
            Toast.makeText(getActivity(),"没价格卖不了呢",Toast.LENGTH_SHORT).show();
        }
        else if (detail.getText().toString().isEmpty())
        {
            Toast.makeText(getActivity(),"少年给点描述吧",Toast.LENGTH_SHORT).show();
        }
        else if(address.getText().toString().isEmpty())
        {
            Toast.makeText(getActivity(),"售卖地址很关键哦", Toast.LENGTH_SHORT).show();
        }else {
            AlertDialog.Builder normalDialog = new AlertDialog.Builder(getActivity());
            normalDialog.setTitle("是否确认发布?");
            normalDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            succPublish();
                        }
                    });
            normalDialog.setNegativeButton("关闭",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //...To-do
                        }
                    });
            // 显示
            normalDialog.show();
        }
    }

    //发布成功
    private void  succPublish() {
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        mtitle = title.getText().toString();
        mprice = price.getText().toString();
        moprice = oprice.getText().toString();
        mdetail = detail.getText().toString();
        maddress = address.getText().toString();
        mtype = type.getSelectedItem().toString();
        mhownew = hownew.getSelectedItem().toString();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd   HH:mm:ss");
        SimpleDateFormat formatter1 = new SimpleDateFormat("ddHHmmss");
        Date curDate =  new Date(System.currentTimeMillis());
        Log.i("Test", "curDate: " + curDate);

        for(int i = 0 ;i < func.getChildCount();i++){
            RadioButton rb = (RadioButton)func.getChildAt(i);
            if(rb.isChecked()){
                mfuc = rb.getText().toString();
                break;
            }
        }

        BooksDetail booksDetail =new BooksDetail();
        booksDetail.setUsername(username);
        // User.getCurrentUser(User.class) 获取当前登录的本地用户信息
        booksDetail.setPushname(User.getCurrentUser(User.class));
        booksDetail.setBook_id(formatter1.format(curDate));
        booksDetail.setBook_name(mtitle);
        booksDetail.setBook_price(mprice);
        booksDetail.setBook_oprice(moprice);
        booksDetail.setBook_detail(mdetail);
        booksDetail.setAddress(maddress);
        booksDetail.setBook_type(mtype);
        booksDetail.setBook_hownew(mhownew);
        booksDetail.setBook_fuc(mfuc);
        booksDetail.setBook_img(filePath.toString());
        booksDetail.save(new SaveListener<String>() {
            @Override
            public void done(String objectid, BmobException e) {
                if(e==null)
                {
                    Toast.makeText(getActivity(), "发布成功！", Toast.LENGTH_SHORT).show();
                }else
                    {
                        Log.e("发布失败", "原因: ",e );
                    }
            }
        });
//        ContentValues values = new ContentValues();
//        values.put("id",formatter1.format(curDate));
//        values.put("username",username);  //保存发布人账号
//        values.put("book_name",mtitle);  //保存书名
//        values.put("book_price",mprice);  //保存现价
//        values.put("book_oprice",moprice);  //保存原价
//        values.put("book_detail",mdetail);  //保存介绍
//        values.put("address",maddress);  //保存地址
//        values.put("book_type",mtype);  //保存类型
//        values.put("book_hownew",mhownew);  //保存新旧程度
//        values.put("book_fuc",mfuc);  //保存送货方式
//        values.put("book_img",filePath.toString());  //保存图片
//        values.put("time",formatter.format(curDate));  //保存发布时间
//        db.insert("BooksDetail",null,values); //执行插入操作

        image.setDrawingCacheEnabled(false);
//        Toast.makeText(getActivity(),"发布成功", Toast.LENGTH_SHORT).show();
    }

    public void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper!=null){
            dbOpenHelper.close();  //关闭数据库连接
        }
    }
}
